package leetcode_数组.sort;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 合并区间
 * <p>算法：排序</p>
 *
 * @author yezh
 * @date 2023/7/28 10:11
 */
public class _56 {

    public static int[][] merge(int[][] intervals) {
        Arrays.sort(intervals, (a, b) -> a[0] != b[0] ? a[0] - b[0] : a[1] - b[1]);
        List<int[]> ans = new ArrayList<>();
        int[] curInterval = intervals[0];
        for (int[] interval : intervals) {
            if (interval[0] <= curInterval[1]) curInterval[1] = Math.max(curInterval[1], interval[1]);
            else {
                ans.add(curInterval);
                curInterval = interval;
            }
        }
        ans.add(curInterval);
        return ans.toArray(new int[0][]);
    }

}
